import { isEmpty } from './validate'
import useStore from '@/stores/userStore.js'
import { baseUrl } from '@/env.config.js'

export const interceptorHandler = () => {
  // 请求拦截，对请求添加loaoding，请求头设置等
  uni.addInterceptor('request', {
    invoke: (params) => {
      const { userInfo, token } = useStore()
      const {
        url,
        loading = {
          title: '加载中...',
          mask: true,
        },
        hideLoading = false,
        header = {},
        noToken,
      } = params
      // 没有url则直接返回
      if (isEmpty(url)) {
        return false
      }
      // 是否需要自动展示load
      if (!hideLoading) {
        uni.showLoading(loading)
      }
      console.log(loading, 'loading')

      // 组装完整url
      params.url = baseUrl + url
      // 是否需要token
      if (noToken !== true && token) {
        header['h-authorization-token'] = token
      }
      params.header = header
      return params
    },
    success: (res, options) => {
      uni.hideLoading()
      const { errMsg, data: resData, statusCode } = res
      const { autoUnpack = true, resField = 'data' } = options
      if (statusCode !== 200) {
        uni.showToast({
          title: errMsg,
          icon: 'none',
        })
      } else {
        const { code, [resField]: data, msg } = resData
        // 是否拆包
        if (autoUnpack) {
          if (!code || code === 200) {
            return Promise.resolve(data)
          } else {
            uni.showToast({
              title: msg,
              icon: 'none',
            })
            return Promise.reject(resData)
          }
        } else {
          return Promise.resolve(resData)
        }
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.log(err)
      const { errMsg = '请求失败，请稍后再试' } = err
      uni.showToast({
        title: errMsg,
        icon: 'none',
      })
      return Promise.reject(err)
    },
  })
  // 跳转拦截（用来拦截未登录的页面跳转）
  const loginAfterPage = []
  uni.addInterceptor('navigateTo', {
    invoke: (params) => {
      const { token } = useStore()
      const { url } = params
      if (loginAfterPage.includes(url) && !token) {
        uni.showToast({
          title: '暂未登录，请先登录',
          mask: true,
          icon: 'none',
        })
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/index' })
        }, 800)
        return false
      }
    },
  })
  uni.addInterceptor('uploadFile', {
    invoke: (params) => {
      const { userInfo, token } = useStore()
      // 组装完整url
      params.url = baseUrl + '/light-basic/fileController/uploadFile'
      params.header = {
        'h-authorization-token': token,
      }
      params.name = 'file'
      return params
    },
    success: (res, options) => {
      uni.hideLoading()
      const { errMsg, data: resData, statusCode } = res
      const { autoUnpack = true, resField = 'obj' } = options
      if (statusCode !== 200) {
        uni.showToast({
          title: errMsg,
          icon: 'none',
        })
      } else {
        let { code, [resField]: data, msg } = JSON.parse(resData)
        // 是否拆包
        if (autoUnpack) {
          if (!code || code === 200) {
            return Promise.resolve(data)
          } else {
            uni.showToast({
              title: msg,
              icon: 'none',
            })
            return Promise.reject(resData)
          }
        } else {
          return Promise.resolve(resData)
        }
      }
    },
  })
}
